package com.fancon.android.gardenjokesx.activity;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

import com.fancon.android.gardenjokesx.GardenJokesBaseActivity;
import com.fancon.android.gardenjokesx.R;
import com.fancon.android.gardenjokesx.adapter.FriendsAdapter;
import com.fancon.android.gardenjokesx.entity.FacebookUser;
import com.fancon.android.gardenjokesx.entity.ReportErrors;
import com.fancon.android.gardenjokesx.entity.TwitterUser;
import com.fancon.android.gardenjokesx.entity.User;
import com.fancon.android.gardenjokesx.rpc.GardenJokesApiConnect;
import com.fancon.android.gardenjokesx.rpc.JsonPaser;
import com.fancon.android.gardenjokesx.social.DatabaseHelper;
import com.fancon.android.gardenjokesx.social.SocialUntil;
import com.fancon.android.gardenjokesx.utils.Constant;
import com.fancon.android.gardenjokesx.utils.UserUtil;
import com.fancon.android.multithread.RequestUI;
import com.fancon.android.ui.widget.FanconProgressBar;

/**
 *
 * @author ThanhHV
 *
 */
public class S041Activity extends GardenJokesBaseActivity{
	private ArrayList<User> mlistUser;
	private FriendsAdapter friendAdapter;
	private ListView listFriends;
	private Button mBtnFollowAll;
	private String user_id = "";
	private String mType = "";
	private String twitterToken = "";
	private String twitterSecret = "";
//	private String facebookToken = "";
	// list user id la ban cua user hien tai tren FB hoac Twitter
	private String listUserID = "";
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.common_list_friends);
		User user = UserUtil.getInfoUserLogin(getApplicationContext());
		if(user != null){
			user_id = user.getUser_id();
		}
		Bundle extras = getIntent().getExtras();
		if(extras != null){
			if(extras.getString(Constant.ID_BUTTON).equals("btnFB")){
				mType = "F";
			}
			if(extras.getString(Constant.ID_BUTTON).equals("btnTwit")){
				mType = "T";
			}
		}
		mBtnFollowAll = (Button)findViewById(R.id.s04_btnFollowAll);
		TextView tvTitleListFriends = (TextView) findViewById(R.id.common_tv_title_list_friends);
		tvTitleListFriends.setText(getString(R.string.s04_1_tv_title_list_friends));
		mlistUser = new ArrayList<User>();
		
		listFriends = (ListView) findViewById(R.id.common_item_list_friends);
		ListFriendRequest request = new ListFriendRequest("S041",S041Activity.this,mType);
		getGlobalState().getRequestQueue().addRequest(request);
		mBtnFollowAll.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				RequestFollow request = new RequestFollow("S041",
						S041Activity.this);
				getGlobalState().getRequestQueue().addRequest(request);
			}
		});
	}
	/*
	 * Request to server to get list friend
	 */
	private class ListFriendRequest extends RequestUI {

		private Activity context;
		private FanconProgressBar mProgressDialog;
		private String type;
		public ListFriendRequest(Object key, Activity activity, String Type) {
			super(key, activity);
			context = activity;
			type = Type;
			mProgressDialog = FanconProgressBar.show(context, context.getString(R.string.common_loading));
		}

		@Override
		public void execute() throws Exception {
			// TODO Auto-generated method stub
			DatabaseHelper db = new DatabaseHelper(S041Activity.this);
			SocialUntil social = new SocialUntil(S041Activity.this);
			if(type.equals("T")){
				TwitterUser twiUser = db.getTwitterUser(user_id);
				if(twiUser != null){
					twitterToken = twiUser.getTwitterToken();
					twitterSecret = twiUser.getTwitterSecret();
				}
				listUserID = social.getFriendIdsTwitter(twitterToken, twitterSecret);
			}
			if(type.equals("F")){
				Log.d("user id", user_id);
				FacebookUser currentFacebookUser = db.getFacebookUser(user_id);
				if(currentFacebookUser != null){
					Log.d("S04_1","fb user: "+ currentFacebookUser.getAccessToken());
					ArrayList<FacebookUser> listFB = new ArrayList<FacebookUser>();
					listFB = social.getFriendIdsFacebook(currentFacebookUser.getAccessToken());
					Log.d("size", listFB.size()+"");
					for (int i = 0; i < listFB.size(); i++) {
						listUserID += listFB.get(i).getFacebookId() + ",";
					}
				}
			}
			Log.d("S041", listUserID);
			//@binhbt-comment
			getFriendFromOtherService(context, removeCharacter(listUserID), user_id, type);
		}

		@Override
		public void executeUI(Exception ex) {
			// TODO Auto-generated method stub
			friendAdapter = new FriendsAdapter(S041Activity.this, mlistUser, user_id);
			listFriends.setAdapter(friendAdapter);
			mProgressDialog.dismiss();
		}
	}
	/*
	 * register follow all user
	 */
	private class RequestFollow extends RequestUI {

		private Activity context;
		private FanconProgressBar mProgressDialog;
		public RequestFollow(Object key, Activity activity) {
			super(key, activity);
			context = activity;
			mProgressDialog = FanconProgressBar.show(context, context.getString(R.string.common_loading));
		}

		@Override
		public void execute() throws Exception {
			// TODO Auto-generated method stub
			//@binhbt-comment
			for(int i = 0;i < mlistUser.size();i++){
				if(mlistUser.get(i).isIs_following() == false){
					if(registerFollow(context, user_id, mlistUser.get(i).getUser_id(), "true") == 1){
						Log.d("vao for", "set is following");
						mlistUser.get(i).setIs_following(true);
					}
				}
			}
		}

		@Override
		public void executeUI(Exception ex) {
			// TODO Auto-generated method stub
			friendAdapter = new FriendsAdapter(S041Activity.this, mlistUser, user_id);
			listFriends.setAdapter(friendAdapter);
			mProgressDialog.dismiss();
		}
		
		
	}
	/**
	 * 
	 * @param list_id
	 * @param user_id
	 * @param type: T if is Twitter or F if is Facebook
	 */
	private void getFriendFromOtherService(Activity context, String list_id,String user_id,String type){
		
		List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
		nameValuePairs.add(new BasicNameValuePair("list_id", list_id));
		nameValuePairs.add(new BasicNameValuePair("user_id", user_id));
		nameValuePairs.add(new BasicNameValuePair("type", type));
		GardenJokesApiConnect api = new GardenJokesApiConnect(context);
		String result = api.execPost(getApplicationContext(), GardenJokesApiConnect.GROUP_S, "searchFriendFromOtherServices", nameValuePairs);
		Log.d("list user", result);
		JsonPaser json = new JsonPaser();
		mlistUser = json.getListUser(result);
	}
	/**
	 * register follow for all user on list friend
	 * @param user_id
	 * @param following_user_id
	 * @param is_following
	 * @return
	 */
	private int registerFollow(Activity context, String user_id, String following_user_id, String is_following){
		
		List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
		nameValuePairs.add(new BasicNameValuePair("user_id", user_id));
		nameValuePairs.add(new BasicNameValuePair("following_user_id", following_user_id));
		nameValuePairs.add(new BasicNameValuePair("is_following", is_following));
		GardenJokesApiConnect api = new GardenJokesApiConnect(context);
		String str = api.execPost(this, GardenJokesApiConnect.GROUP_S, "registerFollowingUser", nameValuePairs);
		JsonPaser json = new JsonPaser();
		ReportErrors report = json.getReport(str);
		Log.d("ket qua dang ki", ""+report.getMessage());
		return report.getResult();
	}
	/**
	 * Remove "," at the end string.
	 * @param str
	 * @return
	 */
	private String removeCharacter(String str){
		if(str.length() >=1){
			return str.substring(0, str.length()-1);
		}
		return str;
	}

}
